#!/bin/bash
LOGOPTS=()
END_AND_BEGIN=()
#argument parsing
while [ -n "$1" ]; do
    case "$1" in
     "-s")
        shift
        END_AND_BEGIN+=("--after=$1")
    ;;
    "-e")
        shift
        END_AND_BEGIN+=("--before=$1")
    ;;
    "-w")
        LOGOPTS+=("-w")
    ;;
    "-C")
        LOGOPTS+=("-C")
		LOGOPTS+=("--find-copies-harder")
    ;;
    "-M")
        LOGOPTS+=("-M")
    ;;
    esac
    shift
done

#test if the directory is a git
git branch &> /dev/null || exit 3
echo "Number of commits per author:"
echo "$author$"
git --no-pager shortlog "${END_AND_BEGIN[@]}" -sn --all
echo "$author$"

AUTHORS=$(git shortlog "${END_AND_BEGIN[@]}" -sn --all | cut -f2 | cut -f1 -d' ')



# for a in $AUTHORS
#  do
#  echo '-------------------' stat_"$CUR_DATE".log
#echo "Statistics for: $a"
#echo -n "Number of files changed: "
#    git log "${LOGOPTS[@]}" "${END_AND_BEGIN[@]}" --all --numstat --format="%n" --author="$a" | grep -v -e "^$" | cut -f3 | sort -iu | wc -l
#echo -n "Number of lines added: "
#    git log "${LOGOPTS[@]}" "${END_AND_BEGIN[@]}" --all --numstat --format="%n" --author="$a" | cut -f1 | awk '{s+=$1} END {print s}'
#echo -n "Number of lines deleted: "
#    git log "${LOGOPTS[@]}" "${END_AND_BEGIN[@]}" --all --numstat --format="%n" --author="$a" | cut -f2 | awk '{s+=$1} END {print s}'
#echo -n "Number of merges: "
#    git log "${LOGOPTS[@]}" "${END_AND_BEGIN[@]}" --all --merges --author="$a" | grep -c '^commit'
#
#  done

CUR_DATE=$(date +%Y%m%d%H%M%S)
LOG_NAME="stat_$CUR_DATE.log"


# 提交次数
echo "<count-commits>" >> $LOG_NAME
for a in $AUTHORS
do
	echo "<count-commit>" >> $LOG_NAME
	echo -n "<author>" >> $LOG_NAME
	echo -n "$a" >> $LOG_NAME
	echo "</author>" >> $LOG_NAME
	echo -n "<count>" >> $LOG_NAME
	git log --author="$a" --oneline | wc -l >> $LOG_NAME
	echo "</count>" >> $LOG_NAME
	echo "</count-commit>" >> $LOG_NAME

done
echo -n "<count-commits>" >> $LOG_NAME


# 文件修改数
echo "<files-changed>" >> $LOG_NAME
for a in $AUTHORS
do
	echo "<file-changed>" >> $LOG_NAME
	echo -n "<author>" >> $LOG_NAME
	echo -n "$a" >> $LOG_NAME
	echo "</author>" >> $LOG_NAME
	echo -n "<files>" >> $LOG_NAME
	git log "${LOGOPTS[@]}" "${END_AND_BEGIN[@]}" --all --numstat --format="%n" --author="$a" | grep -v -e "^$" | cut -f3 | sort -iu | wc -l >> $LOG_NAME
	echo "</files>" >> $LOG_NAME
	echo "</file-changed>" >> $LOG_NAME

done
echo -n "</files-changed>" >> $LOG_NAME

echo "执行完毕"
